import React from 'react';
import styles from './img-list.scss';
import {List, Icon} from 'antd';
import {IMG_DOMAIN} from 'utils/constants';
import actions from 'store/actions/img-repo';
import {getGlobalEvent} from 'utils/eventEmitter';
const eventBus = getGlobalEvent();

class ImgList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currImg: {}
    };
    eventBus.on('onImgUploaded', (img) => {
      this.onSelect(img);
    });
  }

  onSelect(img) {
    this.setState({
      currImg: img
    });
    this.props.onSelect && this.props.onSelect(img.url);
  }

  buildListItem(imgs) {
    const result = [];
    for (let i = 0; i < imgs.length; i++) {
      let selected = false;
      if (imgs[i].id && imgs[i].id === this.state.currImg.id) {
        selected = true;
      }
      result.push(
        <div
          className={styles.col}
          key={imgs[i].id}
          onClick={() => {
            this.onSelect(imgs[i]);
          }}
          role="presentation"
        >
          {imgs[i].url && <img src={`${IMG_DOMAIN}${imgs[i].url}`} style={{width: '100%', height: '100%'}} />}
          {selected && (
            <div className={styles.mock}>
              <Icon type="check" theme="outlined" style={{fontSize: '36px', color: '#1890ff'}} />
            </div>
          )}
        </div>
      );
    }
    return result;
  }

  formatDataSource() {
    const {imgs} = this.props;
    const result = [];
    let temp = [];
    for (let i = 0; i < imgs.length; i++) {
      if (i !== 0 && i % 4 === 0) {
        result.push(temp);
        temp = [];
      }
      temp.push(imgs[i]);
    }
    if (temp.length > 0) {
      const pl = new Array(4 + 1 - temp.length).join(1).split('');
      result.push(temp.concat(pl));
    }
    return result;
  }

  render() {
    const dataSource = this.formatDataSource();
    const {total, dispatch, currTag, currPage} = this.props;
    let pageTotal = parseInt(total / 4, 10);
    if (total % 4 !== 0) {
      pageTotal++;
    }
    if (dataSource.length > 0) {
      return (
        <List
          dataSource={dataSource}
          pagination={{
            onChange: async (page) => {
              await dispatch(actions.queryImgsByTag(currTag, page));
              dispatch(actions.setImgRepoPage(page));
            },
            current: currPage,
            pageSize: 2,
            total: pageTotal
          }}
          renderItem={(item) => (
            <List.Item>
              <div className={styles.row}>{this.buildListItem(item)}</div>
            </List.Item>
          )}
        />
      );
    }
    return <div className={styles.noData}>暂无图片</div>;
  }
}

export default ImgList;
